package kordegi.forumsystem.controller;

import kordegi.forumsystem.common.dto.RegisterDto;
import kordegi.forumsystem.common.lang.Result;
import kordegi.forumsystem.entity.User;
import kordegi.forumsystem.service.UserService;
import kordegi.forumsystem.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kordegi
 * @date 2022.05.05 0:19
 * @Description
 */

@Slf4j
@RestController
public class RegisterController {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;

    @CrossOrigin
    @PostMapping("/register")
    public Result signIn (@Validated @RequestBody RegisterDto registerDto, HttpServletResponse response) {

        boolean flag = userService.signIn(registerDto.getUsername(), registerDto.getPassword(), registerDto.getEmail());
        if (flag == true) {
            log.info("注册成功--" + registerDto.getUsername());
            User user = userService.login(registerDto.getUsername());
            String jwt = jwtUtils.createToken(user.getId());
            response.setHeader("Authorization", jwt);
            response.setHeader("Access-Control-Expose-Headers", "Authorization");

            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("username", user.getUsername());
            map.put("password", user.getPassword());
            map.put("phonenumber", user.getPhonenumber());
            map.put("email", user.getEmail());
            return Result.succ("注册成功",map);
        }else {
            return Result.fail("注册失败----" + registerDto.getUsername());
        }
    }
}
